// pages/addParking/addParking.js
import {
  addParkInfoApi,
  editParkInfoApi,
  getAddedParkApi,
} from "../../api/index.js";
let timeId = 0;
let timeId2 = 0;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    jurisdictionColumns: [
      "裕华区",
      "桥西区",
      "长安区",
      "新华区",
      "高新区",
      "循环化工园区",
    ],
    pubPraColumns: [
      { value: 1, name: "对公" },
      { value: 2, name: "对私" },
    ],
    parkManagerId: "",
    type: "add",
    auditStatus: null,
    agreementVip: true,
    btnDisblay: false,
    disabled: false,
    isExist: 1,
    form: {
      id: null,
      longitude: null, //经度
      latitude: null, //纬度
      parkName: "",
      parkAddress: "",
      totalParkSpace: null,
      jurisdiction: "",
      telephone: null,
      corporateName: "",
      rcvAcctNo: "",
      rcvAcctName: "",
      rcvBankSettleNo: "",
      socialCreditCode: null,
      juridicalPersonName: "",
      juridicalPersonNo: "",
      rcvOpeningBank: "",
      remark: "",
      pubPra: null, //对公对私
    },
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(options);
    if (options.type) {
      if (options.type === "see" || options.type === "old") {
        this.setData({
          disabled: true,
          isExist: 2,
        });
      }
      this.setData({
        type: options.type,
      });
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let { type } = this.data;
    this.setData({
      parkManagerId: wx.getStorageSync("userId"),
    });
    if (type === "edit" || type === "see") {
      this.getParkInfoDetail();
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    clearTimeout(timeId);
    clearTimeout(timeId2); //清除定时器
  },

  // methods

  //   查询车场详情
  getParkInfoDetail() {
    let parkInfoDetail = wx.getStorageSync("parkInfoDetail");
    console.log(parkInfoDetail);
    this.setData({
      form: parkInfoDetail,
    });
    let { pubPra } = this.data.form;
    pubPra = pubPra === 1 ? "对公" : "对私";
    this.setData({
      "form.pubPra": pubPra,
    });
  },

  //   选择地址
  chooseAddress() {
    const { type } = this.data;
    if (type === "old" || type === "see") {
      return;
    }
    let that = this;
    wx.chooseLocation({
      success: (res) => {
        that.setData({
          "form.longitude": res.longitude, //经度
          "form.latitude": res.latitude, //纬度
          "form.parkAddress": res.address,
        });
      },
    });
  },

  //   picker选择区域
  bindPickerJurisdiction(e) {
    const index = e.detail.value;
    this.setData({
      "form.jurisdiction": this.data.jurisdictionColumns[index],
    });
  },
  bindPickerPubPra(e) {
    const index = e.detail.value;
    this.setData({
      "form.pubPra": this.data.pubPraColumns[index].name,
    });
  },

  // 协议按钮
  setAgreementVip() {
    this.setData({
      agreementVip: !this.data.agreementVip,
    });
  },

  // 跳转协议页面
  toAgreement() {
    wx.navigateTo({
      url: "/pages/serviceAgreement/serviceAgreement",
    });
  },

  onSubmit(e) {
    // 获取表单数据
    const formData = e.detail.value;
    Object.keys(formData).forEach((key) => {
      formData[key] = formData[key].trim();
    });
    if (!this.data.parkManagerId) {
      getApp().showToast("userId为null,请重新登录");
      wx.reLaunch({ url: "/pages/login/login" });
      return false;
    }
    if (!formData.parkName) {
      getApp().showToast("请输入停车场名称");
      return false;
    }
    if (!formData.parkAddress) {
      getApp().showToast("请输入停车场地址");
      return false;
    }
    if (!formData.totalParkSpace) {
      getApp().showToast("请输入总车位数");
      return false;
    }
    if (!formData.jurisdiction) {
      getApp().showToast("请输入区域");
      return false;
    }
    const phoneRegex = /^[1][3-9][0-9]{9}$/;
    if (!formData.telephone || !phoneRegex.test(formData.telephone)) {
      getApp().showToast("请输入正确的手机号");
      return false;
    }
    if (!formData.corporateName) {
      getApp().showToast("请输入经营单位");
      return false;
    }
    const socialCreditCode = /^[0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}$/;
    if (
      !formData.socialCreditCode ||
      !socialCreditCode.test(formData.socialCreditCode)
    ) {
      getApp().showToast("请输入正确的统一社会信用代码");
      return false;
    }
    if (!formData.juridicalPersonName) {
      getApp().showToast("请输入法人姓名");
      return false;
    }
    if (!formData.juridicalPersonNo) {
      getApp().showToast("请输入法人身份证号");
      return false;
    }
    if (!formData.pubPra) {
      getApp().showToast("请选择账户类型");
      return false;
    }
    if (formData.pubPra == "对公") {
      if (!formData.proName) {
        getApp().showToast("请输入收款人开户行省名");
        return false;
      }
      if (!formData.cityName) {
        getApp().showToast("请输入收款人开户行市名");
        return false;
      }
      if (!formData.accDept) {
        getApp().showToast("请输入收款人开户行机构名");
        return false;
      }
    }
    if (!formData.rcvOpeningBank) {
      getApp().showToast("请输入银行卡开户行");
      return false;
    }
    if (!formData.rcvAcctName) {
      getApp().showToast("请输入收款账户名");
      return false;
    }
    if (!formData.rcvAcctNo) {
      getApp().showToast("请输入收款账号");
      return false;
    }
    if (!this.data.agreementVip) {
      getApp().showToast("请先阅读并同意车场服务协议");
      return false;
    }

    const { id, latitude, longitude } = this.data.form;
    const { type, parkManagerId, isExist } = this.data;
    formData.parkManagerId = parkManagerId;
    formData.latitude = latitude;
    formData.longitude = longitude;
    formData.isExist = isExist;
    formData.pubPra == "对公" ? (formData.pubPra = 1) : (formData.pubPra = 2);
    if (type === "edit") {
      formData.id = id;
      formData.auditStatus = 0;
      this.editParkInfo(formData);
    } else {
      // 添加
      this.addParkInfo(formData);
    }
    // 阻止表单默认提交行为
    return false;
  },
  // 添加车场
  async addParkInfo(formData) {
    try {
      this.setData({
        btnDisblay: true,
      });
      await addParkInfoApi(formData);
      getApp().showToast("添加成功!");
      this.onReset();
      timeId = setTimeout(() => {
        wx.navigateBack({
          delta: 1,
        });
      }, 1000);
    } catch (error) {
      //   console.log(error);
      getApp().showToast("添加失败,请重试!");
    } finally {
      this.setData({
        btnDisblay: false,
      });
    }
  },

  // 修改车场
  async editParkInfo(formData) {
    try {
      this.setData({
        btnDisblay: true,
      });
      await editParkInfoApi(formData);
      getApp().showToast("修改成功!");
      this.onReset();
      timeId = setTimeout(() => {
        wx.navigateBack({
          delta: 1,
        });
      }, 1000);
    } catch (error) {
      //   console.log(error);
      getApp().showToast("修改失败,请重试!");
    } finally {
      this.setData({
        btnDisblay: false,
      });
    }
  },

  //   表单重置
  onReset() {
    this.setData({
      form: {},
    });
  },

  // 查询已有车场
  bindInputSearchPark(e) {
    const { value } = e.detail; //拿到输入框中的值
    clearTimeout(timeId2); //清除定时器
    timeId2 = setTimeout(() => {
      if (value) {
        this.searchParkApi(value);
      }
    }, 1000);
  },

  // 通过名称查询车场api
  async searchParkApi(parkName) {
    try {
      const { data: res } = await getAddedParkApi({ parkName });
      if (res.data.parkName) {
        console.log(res.data);
        this.setData({
          form: res.data,
        });
      }
    } catch (error) {}
  },
});
